app.controller('ConfigCtrl', [
    '$scope', 'notification', 'configSerivce',
    function ($scope, notification, configSerivce) {

        configSerivce.loadAsync()
            .then(function (result) {
                angular.forEach(result, function (v) {
                    v.readOnly = true;
                    v.oldValue = v.Value;
                });
                $scope.configList = result;
            }, notification.error);

        $scope.update = function (config) {
            if (config.readOnly) {
                config.readOnly = false;
                return;
            } 
            if (config.Value == config.oldValue) {
                return;
            }
            configSerivce.addOrUpdateAsync(config.Key, config.Value, config.Remark)
                .then(function () {
                    config.readOnly = true;
                    config.oldValue=config.Value;
                }, notification.error);
        };

        $scope.reset=function(config){
            config.Value=config.oldValue;
            config.readOnly=true;
        };
    }
]);

app.factory('configSerivce', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.loadAsync = function () {
            var q = $q.defer();
            $http({ url: '/api/config' })
                .success(function (result) {
                    if (result.Code >= 0) {
                        q.resolve(result.Data);
                    } else {
                        q.reject(result.Message);
                    }
                }).error(function (x) {
                    q.reject('获取系统参数配置失败');
                    console.error(x);
                });
            return q.promise;
        };

        self.addOrUpdateAsync = function (key, value, remark) {
            var q = $q.defer();
            $http({
                url: '/api/config',
                method: 'POST',
                params: {
                    key: key,
                    value: value,
                    remark: remark
                }
            })
                .success(function (result) {
                    if (result.Code >= 0) {
                        q.resolve(result.Data);
                    } else {
                        q.reject(result.Message);
                    }
                }).error(function (x) {
                    q.reject('更新系统参数配置失败');
                    console.error(x);
                });
            return q.promise;
        };

        return self;
    }
]);